package cn.duckerkj.util.safeutil;


import java.security.MessageDigest;
import java.util.Arrays;

public class SignUtil {
	public boolean checkSignature(){
		//获取报文中签名
		String signature ="signature";
		//获取特定参数
		String timestamp = "timestamp";
		String nonce = "nonce";
		//添加一个默认数据
		ConfigUtil.setPropertiesName("config.properties");
		ConfigUtil.init();
		String token = ConfigUtil.getValue("wxToken");
		//排序
		String[] tmpArr = { token, timestamp, nonce };
		Arrays.sort(tmpArr);
		String tmpStr = this.ArrayToString(tmpArr);
		//sha1加密
		tmpStr = this.SHA1Encode(tmpStr);
		//验证签名
		if (tmpStr.equalsIgnoreCase(signature)) {
			return true;
		} else {
			return false;
		}
	}
	public String SHA1Encode(String sourceString) {
		String resultString = null;
		try {
		   resultString = new String(sourceString);
		   MessageDigest md = MessageDigest.getInstance("SHA-1");
		   resultString = byte2hexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
		}
		return resultString;
	}
	public final String byte2hexString(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
		    	buf.append("0");
		   	}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString().toUpperCase();
	}
	public String ArrayToString(String [] arr){
		StringBuffer bf = new StringBuffer();
		for(int i = 0; i < arr.length; i++){
		 bf.append(arr[i]);
		}
		return bf.toString();
	}
}
